package com.ruoyi.doorcontrol.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.doorcontrol.domain.*;
import com.ruoyi.doorcontrol.service.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

//访客控制器
@RequestMapping("/visit/visitList")
@RestController
public class YivisitController extends BaseController {

    @Autowired
    private IThDoorControlService thDoorControlService;
    @Autowired
    private IThDoorcontrolUserService thDoorcontrolUserService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private HkUserService hkUserService;
    @Autowired
    private HkFaceService hkFaceService;
    @Value("${ruoyi.serverip}")
    private String serverip;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IThGateControlService thGateControlService;
    @Autowired
    private IZyCarService zyCarService;
    @Autowired
    private IThOpengateRecordsService thOpengateRecordsService;
    @PostMapping("/setControl")
    //private void setControl(List<ThDoorControl> controlList,YiVisit visit){
    public AjaxResult setControl(@RequestBody Map<String,Object> map){

        HttpServletRequest request = ServletUtils.getRequest();
        String ipAddress = HttpUtils.getIpAddress(request);
        /*if(null == ipAddress){
            throw new CustomException("获取请求的ip失败！");
        }else if(!serverip.contains(ipAddress)){
            System.out.println(serverip+"门禁中来自服务器的请求地址是："+ipAddress);
            throw new CustomException("请求地址错误！");
        }*/

        System.out.println("-----------------接收到门禁添加用户的请求-----------------");
        //List<ThDoorControl> controlList = (List<ThDoorControl>)map.get("controlList");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        ThDoorControl control = new ThDoorControl();
        control.setControlPosition("menfang");
        List<ThDoorControl> controlList = thDoorControlService.selectThDoorControlList(control);

        YiVisit visit = JSON.parseObject(JSON.toJSONString(map.get("visit")), YiVisit.class);
        SysDictData sysDictData = sysDictDataService.selectDictValue("zy_visit","visit_effective_leave");
        ThDoorcontrolUser user = new ThDoorcontrolUser();
        user.setUname(visit.getName());
        user.setBeginTime(visit.getUpdateTime());
        user.setEmployeeNo(visit.getEmployeeNo());
        user.setUserType("visitor");//访客
        user.setEnable("true");
        user.setPhonenumber(visit.getPhone());
        user.setPhoto(visit.getPhoto());
        user.setCompany(visit.getCompany());
        user.setFroms(visit.getFroms());
        user.setVisitName(visit.getVisitName());
        user.setVisitBumen(visit.getVisitBumen());
        user.setVisitInfo(visit.getVisitInfo());
        user.setPlateNum(visit.getCar());

        Calendar cal = Calendar.getInstance();
        cal.setTime(visit.getUpdateTime());
        cal.add(Calendar.HOUR,Integer.parseInt(sysDictData.getDictValue()));// 24小时制
        Date control_endTime = cal.getTime();//门房出门的门禁机结束时间
        ThDoorcontrolUser oldUser = new ThDoorcontrolUser();//根据用户名称 手机号查询用户
        oldUser.setPhonenumber(user.getPhonenumber());
        oldUser.setUname(user.getUname());
        oldUser.setStatus("0");
        List<ThDoorcontrolUser> thDoorcontrolOldUsers = thDoorcontrolUserService.selectThDoorcontrolUserList(oldUser);

        boolean flag = true;
        for (ThDoorControl thDoorControl : controlList) {
            for (ThDoorcontrolUser thDoorcontrolOldUser : thDoorcontrolOldUsers) {
                AjaxResult ajaxResult = hkUserService.deleteUserInfo(thDoorControl, thDoorcontrolOldUser.getEmployeeNo());

            }
            if(thDoorControl.getControlPosition().contains("in")){
                user.setEndTime(visit.getEndTime());
                System.out.println("-------开始添加用户------");



                AjaxResult ajaxResult = hkUserService.addUser(thDoorControl,user);
                if(200 != Integer.parseInt(ajaxResult.get("code").toString())){
                    logger.info("访客"+visit.getName()+"录入"+thDoorControl.getNotes()+"失败！");
                    throw new CustomException("访客"+visit.getName()+"录入"+thDoorControl.getNotes()+"失败！");
                }
                System.out.println("-----添加用户结束-----"+ajaxResult.toString());

                System.out.println("下发人脸接口：thDoorControl="+thDoorControl.toString()+"-----userEmployeeNo="+user.getEmployeeNo()+"----visitPhoto="+visit.getPhoto());
                AjaxResult faceAjaxResult = hkFaceService.addFaceByBinary(thDoorControl,user.getEmployeeNo(), visit.getPhoto());
                if(200 != Integer.parseInt(faceAjaxResult.get("code").toString())){
                    flag = false;
                }
            }

            if(thDoorControl.getControlPosition().contains("out")){
                user.setEndTime(control_endTime);
                AjaxResult ajaxResult = hkUserService.addUser(thDoorControl,user);
                if(200 != Integer.parseInt(ajaxResult.get("code").toString())){
                    throw new CustomException("访客"+visit.getName()+"录入"+thDoorControl.getNotes()+"失败！");
                }
                AjaxResult faceAjaxResult = hkFaceService.addFaceByBinary(thDoorControl,user.getEmployeeNo(), visit.getPhoto());
                if(200 != Integer.parseInt(faceAjaxResult.get("code").toString())){
                    flag = false;
                }
            }
        }
        int i = thDoorcontrolUserService.batchupdateThDoorcontrolUser(thDoorcontrolOldUsers);

        AjaxResult ajaxResult = new AjaxResult();
        if(!flag){
            visit.setStatus("0");
            ajaxResult.put("code",201);
            ajaxResult.put("msg","访客人脸下发失败！");
        }else {
            visit.setStatus("1");
            ajaxResult.put("code",200);
        }

        user.setEndTime(control_endTime);
        user.setStatus("0");
        Map<String,Object> param_map = new HashMap<>();
        param_map.put("method","updateVisit");
        param_map.put("visit",visit);
        try {
            System.out.println("访客人脸下发修改正式数据库中访客的状态-status=="+user.getStatus());
            HttpUtils.sendPost2(serverip+"/visit/visitList",param_map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        thDoorcontrolUserService.insertThDoorcontrolUser(user);
        return ajaxResult;
    }


    /**
     * 停车场post请求
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/parking")
    public String parking(HttpServletRequest request, HttpServletResponse response){
        ParkingRequest parking = new ParkingRequest();
        // 获取请求参数
        Enumeration<String> parameterNames = request.getParameterNames();
        //getQueryString
        Map<String,String> type_map = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);

            String parameter = request.getParameter(paramName);
            //System.out.println("parameter:"+parameter);
            for (int i = 0; i < paramValues.length; i++) {
                //System.out.println("参数名称: " + paramName + ", 参数值: " + paramValues[i]);
                builder.append(paramName+"="+paramValues[i]+"&");
            }

            if(paramName.equals("type")){
                type_map.put("type",request.getParameter(paramName));
            }



            /*if(paramName.equals("type") && request.getParameter(paramName).equals("heartbeat")){//心跳

                parking.setError_num(0);
                parking.setError_str("error info");
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(parking));
                return jsonObject;


            }

            if(paramName.equals("type") && request.getParameter(paramName).equals("online") ){//正常在线传输结果
                String plate_num = request.getParameter("plate_num");
                if(StringUtils.isNotBlank(plate_num)){
                    String visit_effective_time = configService.selectConfigByKey2("visit_effective_time");
                    List<YiVisit> yiVisits = yiVisitService.selectYivisitByplateNum(StringUtils.deleteWhitespace(plate_num), visit_effective_time);
                    if(yiVisits.size()>0){
                        parking.setError_num(0);
                        parking.setError_str("error info");
                        List<Map<String,Object>> list = new ArrayList<>();
                        Map<String,Object> map = new HashMap<>();
                        map.put("ionum","io1");
                        map.put("action","on");
                        list.add(map);
                        parking.setGpio_data(list);
                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(parking));
                        //System.out.println("返回响应："+jsonObject);
                        return jsonObject;
                    }
                }
            }*/
        }
        String xintiao =  "HTTP/1.1 200\rContent-Type:application/json;charset=utf-8\rContent-Length:81\r\n\r\n"+"{\"error_num\":0,\"error_str\":\"noerror\",\"gpio_data\":[{\"ionum\":\"io1\",\"action\":\"on\"}]}";

        String kaimen =  "HTTP/1.1 200\rContent-Type:application/json;charset=utf-8\rContent-Length:81\r\n\r\n"+
                //"{\"error_num\":0,\"error_str\":\"noerror\",\"gpio_data\":[{\"ionum\":\"io1\",\"action\":\"on\"}]}";
                "{\"error_num\":0,\"error_str\":\"noerror\",\"gpio_data\":[{\"ionum\":\"io1\",\"action\":\"on\"}],\"rs485_data\":["+
                "{\"encodetype\":\"hex2string\",\"data\":\"e7acace4b880e8a18ce698bee7a4ba\"},{\"encodetype\":\"hex2string\",\"data\": \"e7acace4ba8ce8a18ce698bee7a4ba\"},{\"encodetype\":\"hex2string\",\"data\":\"e58fafe4bba5e8bf9be585a5\"}]}";

        String remoteAddr = request.getRemoteAddr();
        String substring = builder.toString().substring(0, builder.toString().length() - 1);
        //int i = yiVisitService.insertParking(remoteAddr,substring);


        if(type_map.containsKey("type") && type_map.get("type").equals("heartbeat")){//心跳

            parking.setError_num(0);
            parking.setError_str("error info");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(parking));


            Set<String> keys = redisTemplate.keys("openGate");//远程开道闸
            if (CollectionUtils.isNotEmpty(keys)) {
                String openGate_ip = redisTemplate.opsForValue().get("openGate").toString();
                if(remoteAddr.equals(openGate_ip)){
                    redisTemplate.delete(keys);
                    return kaimen;
                }
            }

            return xintiao;


        }

        if(type_map.containsKey("type") && type_map.get("type").equals("online") ){//正常在线传输结果

            ThGateControl thGateControl = new ThGateControl();
            thGateControl.setStatus("0");
            List<ThGateControl> ZyDoorControllist = thGateControlService.selectThGateControlList(thGateControl);
            boolean flag = false;
            for (ThGateControl gateControl : ZyDoorControllist) {
                if(gateControl.getIpadress().equals(remoteAddr)){
                    flag = true;
                }
            }
            if(!flag){
                return "";
            }

            String plate_num = request.getParameter("plate_num");
            if(StringUtils.isNotBlank(plate_num)){
                //先查询本地的车辆信息
                ThOpengateRecords thOpengateRecords = new ThOpengateRecords();
                thOpengateRecords.setIp(remoteAddr);//ip
                thOpengateRecords.setPlateNum(plate_num);//车牌
                thOpengateRecords.setPlateNumColor(request.getParameter("color"));
                thOpengateRecords.setVehicleType(request.getParameter("VehicleType"));
                thOpengateRecords.setCarLogo(request.getParameter("car_logo"));
                thOpengateRecords.setStartTime(request.getParameter("start_time"));
                thOpengateRecords.setParkId(Long.parseLong(request.getParameter("park_id")));
                thOpengateRecords.setCameraId(request.getParameter("camera_id"));
                thOpengateRecords.setPicture(request.getParameter("picture"));
                thOpengateRecords.setCloseupPic(request.getParameter("closeup_pic"));


                ZyCar car = zyCarService.selectZyCarByPlateNum(plate_num);
                if(null !=car && car.getStatus().equals("0") && car.getIsDelete().equals("0")){
                    thOpengateRecords.setCarType("0");//内部车辆
                    int i1 = thOpengateRecordsService.insertThOpengateRecords(thOpengateRecords);
                    return kaimen;
                }else {
                    String visit_effective_time = configService .selectConfigByKey2("visit_effective_time");
                    //List<YiVisit> yiVisits = yiVisitService.selectYivisitByplateNum(StringUtils.deleteWhitespace(plate_num), visit_effective_time);
                    List<ThDoorcontrolUser> thDoorcontrolUser = thDoorcontrolUserService.selectByVisitPlateNum(StringUtils.deleteWhitespace(plate_num), visit_effective_time);
                    if(thDoorcontrolUser.size()>0){
                        parking.setError_num(0);
                        parking.setError_str("error info");
                        List<Map<String,Object>> gpio_data_list = new ArrayList<>();
                        Map<String,Object> gpio_data_map = new HashMap<>();
                        gpio_data_map.put("ionum","io1");
                        gpio_data_map.put("action","on");
                        gpio_data_list.add(gpio_data_map);
                        parking.setGpio_data(gpio_data_list);
                        List<Map<String,Object>> rs485_data_list = new ArrayList<>();
                        Map<String,Object> rs485_data_map1 = new HashMap<>();
                        Map<String,Object> rs485_data_map2 = new HashMap<>();
                        Map<String,Object> rs485_data_map3 = new HashMap<>();
                        rs485_data_map1.put("encodetype","hex2string");
                        rs485_data_map2.put("encodetype","hex2string");
                        rs485_data_map3.put("encodetype","hex2string");
                        rs485_data_map1.put("data",plate_num);
                        rs485_data_map2.put("data","访客车辆");
                        rs485_data_map3.put("data","欢迎光临");
                        rs485_data_list.add(rs485_data_map1);
                        rs485_data_list.add(rs485_data_map2);
                        rs485_data_list.add(rs485_data_map3);
                        parking.setRs485_data(rs485_data_list);
                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(parking));
                        //System.out.println("返回响应："+jsonObject);
                        thOpengateRecords.setCarType("1");//访客车辆
                        int i1 = thOpengateRecordsService.insertThOpengateRecords(thOpengateRecords);
                        return kaimen;
                    }
                    //return jsonObject;
                }
            }
        }

        return null;
    }

}
